#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/11 9:27
# @Author  : FuKai ZHANG
# @File    : cache_control.py
# @Description :缓存控制文件
import json
from typing import Dict
from utils.cache_tools.redis_control import RedisHandler


class CacheHandler(object):
    # 序列化
    @staticmethod
    def _serialize_case_data(case_data: Dict) -> Dict:
        """
        将字典数据转换为字符串，并确保Redis兼容
        列表字典等复杂Python对象不能直接存到hash  需要将其序列化为Json字符串
        """
        serialized_data = {}
        for key, value in case_data.items():
            if isinstance(value, (dict, list)):
                serialized_data[key] = json.dumps(value)
            else:
                serialized_data[key] = str(value) if value is not None else ""
                # 空值和其他值强制转换  确保Redis兼容
        return serialized_data

    # 反序列化
    @staticmethod
    def _deserialize_case_data(hash_data: Dict) -> Dict:
        """
        反序列化测试用例数据，JSON字符串转为字典
        :param hash_data: Redis Hash 数据
        :return: 反序列化后的字典
        """
        if not hash_data:
            return {}
        deserialized_data = {}
        for key, value in hash_data.items():
            if key in ['headers', 'data', 'expected', 'extract'] and value:
                try:
                    deserialized_data[key] = json.loads(value)#反序列化，将JSON字符串转为字典
                except json.JSONDecodeError:
                    deserialized_data[key] = None
            else:
                deserialized_data[key] = value if value != "" else None
        return deserialized_data
    @staticmethod
    def set_case_data_cache(name: str, value: Dict) -> None:
        """
        设置缓存，将 value（字典）序列化后存储为 Redis Hash
        :param name: 缓存名称（如 case_id）
        :param value: 缓存值（字典）
        """
        redis_handler = RedisHandler()
        serialized_data = CacheHandler._serialize_case_data(value)
        redis_key = f"case:{name}"
        redis_handler.set_hash(redis_key, serialized_data)



    @staticmethod
    def get_case_cache(name: str) -> Dict[str, object]:
        """
        读取缓存，返回字典
        :param name: 缓存名称
        :return: JSON 字符串或 None
        """
        redis_handler = RedisHandler()
        redis_key = f"case:{name}"
        hash_data = redis_handler.get_hash(redis_key)
        deserialized_data = CacheHandler._deserialize_case_data(hash_data)
        return deserialized_data if deserialized_data else None

    @staticmethod
    def set_string(name: str, value: str) -> None:
        """
        设置缓存，将 value（字符串）存储为 Redis 字符串
        :param name: 缓存名称
        :param value: 缓存值（字符串）
        """
        redis_handler = RedisHandler()
        redis_handler.set_string(name, value)
    @staticmethod
    def get_string(name: str) -> str:
        """
        获取缓存，返回字符串
        :param name: 缓存名称
        :return: 缓存值（字符串）
        """
        redis_handler = RedisHandler()
        return redis_handler.get_string(name)
    @staticmethod
    def clean_cache() -> None:
        """
        清理所有缓存
        """
        RedisHandler().del_all_cache()


# def set_cookie_cache(pattern: str, string: str) -> None:
#     """
#     设置 cookie 缓存，仅适用于当前项目,可以根据需要自行修改
#     :param pattern: 匹配 cookie 的正则表达式
#     :param string: 待匹配的字符串
#     """
#     match = re.search(pattern, string)
#     if match:
#         cookie_value = match.group(1)
#         cookie_data = {"value": f"JSESSIONID={cookie_value}"}
#         CacheHandler.set_cache('Cookie', cookie_data)
#     else:
#         raise ValueError("No cookie found in the provided string")


if __name__ == '__main__':
    pass
